import {
  getVendInfoList,
  addVend,
  updateVend,
  deleteVend,
} from "@/api/basicData/equipmentManagement.js";
export const myMethod = {
  // 切换条数
  handleSizeChange(val) {
    this.pageSize = val;
    this.currentPage = 1;
    this.getTableData();
  },
  // 切换页码
  handleCurrentChange(val) {
    this.currentPage = val;
    this.getTableData();
  },
  // 点击查询操作
  queryChange(val) {
    this.form = Object.assign(this.form, val);
    this.currentPage = 1;
    this.getTableData();
  },
  // 重置查询数据
  resetPage() {
    this.pageSize = 15;
    this.currentPage = 1;
    this.totalPage = 0;
    this.$refs.dataTableRef.tableData = [];
    this.form = {};
  },
  // 获取列表数据
  async getTableData() {
    this.$refs.dataTableRef.tableLoading = true;
    try {
      const { WorkOrderCode } = this.form;
      const params = {
        VendName: WorkOrderCode || "", // 设备名称
        rows: this.pageSize,
        page: this.currentPage,
      };
      console.log(params);
      const res = await getVendInfoList(params);
      if (res.status === 0) {
        this.$refs.dataTableRef.tableData = res.rows || [];
        this.totalPage = res.total || 0;
      } else {
        this.$refs.dataTableRef.tableData = [];
        this.totalPage = 0;
        this.$message.error(res.msg || "查询失败");
      }
      this.$refs.dataTableRef.tableLoading = false;
    } catch (err) {
      this.$message.error(err.msg || "查询失败");
      this.$refs.dataTableRef.tableLoading = false;
    }
  },
  showVendStatus(val) {
    // 设备状态 1运行, 2待机, 3停机, 4故障, 5维修中
    const statusMap = {
      1: '运行',
      2: '待机',
      3: '停机',
      4: '故障',
      5: '维修中'
    };
    return statusMap[Number(val)] || '--';
  },
  addChange() {
    this.addTitle = "添加设备";
    this.$refs.addDialogComRef.dialogVisible = true;
  },
  // 清空弹框的数据
  closeChange() {
    this.vendInfo = {
      vendStatus: 1
    };
    this.$refs.vendInfoRef.clearValidate();
  },
  // 确认提交操作
  confirmChange() {
    this.$refs.vendInfoRef.validate(async (valid) => {
      if (valid) {
        try {
          this.$refs.addDialogComRef.loading = true;
          const {
            vendCode,
            vendName,
            vendModel,
            vendStatus,
            remark,
          } = this.vendInfo;
          const params = {
            vendCode: vendCode, // 设备编码
            vendName: vendName, // 设备名称
            vendModel: vendModel, // 设备型号
            vendStatus: vendStatus, // 设备状态
            remark: remark || "", // 备注
          };
          const isAdd = !this.vendInfo.qualityDetectionProjectId
          const text = isAdd ? "添加" : "修改"
          if(!isAdd) {
            params.qualityDetectionProjectId = this.vendInfo.qualityDetectionProjectId
          }
          const apiName = isAdd ? addVend : updateVend
          const result = await apiName(params);
          if (result.ok) {
            this.$message.success(text+ "成功");
            this.$refs.addDialogComRef.dialogVisible = false;
            if(isAdd) this.currentPage = 1
            this.closeChange();
            this.getTableData();
          } else {
            this.$message.error((result.err&&result.err.msg) || (text+ "失败"));
          }
          this.$refs.addDialogComRef.loading = false;
        } catch (err) {
          this.$refs.addDialogComRef.loading = false;
          console.error(text + "数据异常:", err);
        }
      }
    });
  },
  detailChange(val) {
    this.updateChange(val)
  },
  updateChange(val) {
    this.addTitle = "修改设备";
    this.vendInfo = JSON.parse(JSON.stringify(val));
    this.vendInfo.vendModel = this.vendInfo.vend_Model;
    this.$refs.addDialogComRef.dialogVisible = true;
  },
  async deleteChange(val) {
    // delNum用于切换页码
    const oldCurrentPage = this.currentPage;
    const temp = Math.ceil(Math.max(this.totalPage - 1, 1) / this.pageSize);
    if (this.currentPage > temp) {
      this.currentPage = temp;
    }
    this.$refs.dataTableRef.tableLoading = true;
    try {
      const params = {
        id: val.vendId || "" // 设备id
      };
      const res = await deleteVend(params);
      if (res.ok) {
        this.$message.success("删除成功");
        this.getTableData()
      } else {
        this.currentPage = oldCurrentPage
        this.$message.error(res.msg || "删除失败");
      }
      this.$refs.dataTableRef.tableLoading = false;
    } catch (err) {
      this.currentPage = oldCurrentPage
      this.$message.error(err.msg || "删除失败");
      this.$refs.dataTableRef.tableLoading = false;
    }
  },
  async downloadImg() {
    if(!this.vendInfo.vendQRCode) {
      return this.$message.error('地址有误');
    }
    try {
    const imageUrl = this.vendInfo.vendQRCode.replace(process.env.VUE_APP_API, process.env.VUE_APP_RESOURCE)
    const response = await fetch(imageUrl);
    const blob = await response.blob();
    const blobUrl = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = blobUrl;
    link.download = `设备二维码_${this.vendInfo.vendCode || 'unknown'}.png`;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(blobUrl);
    this.$message.success('下载成功');
  } catch (error) {
    console.error('下载失败:', error);
    this.$message.error('下载失败，请重试');
  }
}
};
